package edu.wtbu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import edu.wtbu.dao.UserDao;
import edu.wtbu.pojo.Result;

/**
 * Servlet implementation class AdduserServlet
 */
@WebServlet("/AdduserServlet")
public class AdduserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdduserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter printWriter=response.getWriter();
		
		List<String> paList=new ArrayList<String>();
		Enumeration enumeration=request.getParameterNames();
	    while (enumeration.hasMoreElements()) {
			String object = (String) enumeration.nextElement();
			String[] valStrings=request.getParameterValues(object);
			paList.add(valStrings[0]);
			
		}
	    
	    String paString;
	    if(paList.get(0).length()<6)
	    {
	    	paString=paList.get(0);
	    }
	    else {
	    	paString=paList.get(0).substring(0,6);
		}
	    paList.add(paString);
	    Boolean isBoolean=UserDao.findbyemail(paList.get(0));
	    if(isBoolean)
	    {
	    	Result rr=new Result("邮箱已存在",null,null);
			String mString=JSON.toJSONString(rr);
			printWriter.append(mString);
			return;
	    }
	    UserDao.adduser(paList);
	    Result rr=new Result("success",null,null);
		String mString=JSON.toJSONString(rr);
		printWriter.append(mString);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
